package com.future.service.impl;


import com.future.service.TradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Service
@Qualifier(value = "tradeServiceImpl")
public class TradeServiceImpl extends CommonService implements TradeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TradeServiceImpl.class);

    /**
     * 减库存
     */
    @Override
    public String lock() {
        String res = "";
        try {
            lock.lock();
            Integer stock;
            List<Map<String, Object>> result = jdbcTemplate.queryForList("select stock from t_stock where id=1");
            if (result == null || (stock = (Integer) result.get(0).get("stock")) <= 0) {
                LOGGER.error("下单失败，已经没有库存！");
                res = "下单失败，已没有库存";
            } else {
                stock--;
                jdbcTemplate.update("update t_stock set stock=? where id=1", stock);
                doDBUpdate(stock);
                LOGGER.info("下单成功，当前剩余产品数 -------------------->" + stock);
                res = "下单成功，当前剩余产品数： ------------->" + stock;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return res;
    }

}
